package cn.edu.scau.cmi.ema.service;

import java.util.List;
import java.util.Set;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;


import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.util.CmiSqlUtil;
import cn.edu.scau.cmi.ema.domain.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiEmaService;

import java.io.IOException;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import javax.persistence.Query;
import java.util.Iterator;
@Service("StandardtypeService")
@Transactional

public class StandardtypeServiceImpl extends CmiEmaService implements StandardtypeService {
	public StandardtypeServiceImpl() {
	}

	@Transactional
	public Standardtype saveStandardtype(Standardtype standardtype) {
		Set<Standard> existingStandardsForStandardtype = new HashSet<Standard>();

		Set<Standard> selectedStandardsForStandardtype = standardtype.getStandardsForStandardtype();

		if (standardtype.getId() == null) {

			Standardtype existingStandardtype = standardtypeDAO
					.findStandardtypeByPhysicalPrimaryKey(standardtype.getName());

			if (isEquals(standardtype, existingStandardtype)) {
				return existingStandardtype;
			}

			standardtype = standardtypeDAO.store(standardtype);
			standardtypeDAO.flush();

			for (Standard relatedStandard : selectedStandardsForStandardtype) {
				relatedStandard.setStandardtype(standardtype);
				standardDAO.store(relatedStandard);
			}
		} else {
			Standardtype existingStandardtype = standardtypeDAO.findStandardtypeByPrimaryKey(standardtype.getId());

			existingStandardsForStandardtype = existingStandardtype.getStandardsForStandardtype();

			Set<Standard> prepareDeleteStandardsForStandardtype = new HashSet<Standard>();
			Set<Standard> prepareAddStandardsForStandardtype = new HashSet<Standard>();

			prepareDeleteStandardsForStandardtype.addAll(selectedStandardsForStandardtype);
			prepareDeleteStandardsForStandardtype.addAll(existingStandardsForStandardtype);

			prepareAddStandardsForStandardtype.addAll(selectedStandardsForStandardtype);
			prepareAddStandardsForStandardtype.addAll(existingStandardsForStandardtype);

			prepareDeleteStandardsForStandardtype.removeAll(selectedStandardsForStandardtype);
			prepareAddStandardsForStandardtype.removeAll(existingStandardsForStandardtype);

			for (Standard relatedStandard : prepareAddStandardsForStandardtype) {
				relatedStandard.setStandardtype(standardtype);
				standardDAO.store(relatedStandard);
			}

			for (Standard relatedStandard : prepareDeleteStandardsForStandardtype) {
				relatedStandard.setStandardtype(null);
				standardDAO.store(relatedStandard);
			}
			standardtype = standardtypeDAO.store(standardtype);
			standardtypeDAO.flush();
		}

		standardDAO.flush();
		return standardtype;
	}

	public void deleteStandardtype(Standardtype standardtype) {
		standardtypeDAO.remove(standardtype);
		standardtypeDAO.flush();
	}

	@Transactional
	public void deleteStandardtypes(Set<Integer> deleteStandardtypesId) {
		Query query = standardtypeDAO.createNamedQuery("deleteStandardtypesById", -1, -1);
		query.setParameter(1, deleteStandardtypesId);
		query.executeUpdate();
	}

	@Transactional
	public Set<Standardtype> loadStandardtypes() {
		return standardtypeDAO.findAllStandardtypes();

	}

	@Transactional
	public Set<Standardtype> loadReferenceStandardtypes(Set<Standardtype> standardtypes) {
		Iterator<Standardtype> standardtypesIterator = standardtypes.iterator();
		Set<Standardtype> referencedStandardtypes = new HashSet<>();
		while (standardtypesIterator.hasNext()) {
			Standardtype currentStandardtype = standardtypesIterator.next();

			if (!currentStandardtype.getStandardsForStandardtype().isEmpty()) {
				referencedStandardtypes.add(currentStandardtype);
				continue;
			}
		}
		return referencedStandardtypes;
	}

	public Set<Standardtype> loadStandardtypesByIdSet(Set<Integer> standardtypeIdSet) {

		Iterator<Integer> standardtypeIdIterator = standardtypeIdSet.iterator();
		Set<Standardtype> standardtypeSet = new HashSet<>();
		while (standardtypeIdIterator.hasNext()) {
			Integer id = standardtypeIdIterator.next();
			Standardtype currentStandardtype = standardtypeDAO.findStandardtypeById(id);
			standardtypeSet.add(currentStandardtype);
		}
		return standardtypeSet;
	}

	@Transactional
	public List<Standardtype> findAllStandardtypes(Integer startResult, Integer maxRows) {
		return new java.util.ArrayList<Standardtype>(standardtypeDAO.findAllStandardtypes(startResult, maxRows));
	}

	@Transactional
	public Standardtype findStandardtypeByPrimaryKey(Integer id) {
		return standardtypeDAO.findStandardtypeByPrimaryKey(id);
	}

	@Transactional
	public Integer countStandardtypes() {
		return ((Long) standardtypeDAO.createQuerySingleResult("select count(o) from Standardtype o").getSingleResult())
				.intValue();
	}

	@Transactional
	public Integer countStandardtypes(CmiPagination page) {
		String sql = CmiSqlUtil.createCountHql(page, Standardtype.class);
		return ((Long) standardtypeDAO.createQuerySingleResult(sql).getSingleResult()).intValue();
	}

	/**
	 * search for name with ajax
	 * 
	 */
	@Transactional
	public Integer countStandardtypesByName(String queryName) {
		Query query = standardtypeDAO.createNamedQuery("countStandardtypesByName", -1, -1);
		query.setParameter(1, queryName);
		return new Long((long) query.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countStandardtypesByDetachedCriteria(CmiPagination page) {
		DetachedCriteria detachedCriteria = CmiSqlUtil.createDetachedCriteria(page, Standardtype.class);
		Session session = entityManager.unwrap(Session.class);
		detachedCriteria.setProjection(Projections.rowCount());
		return new Long((long) detachedCriteria.getExecutableCriteria(session).uniqueResult()).intValue();
	}

	public Map<String, ?> loadStandardtypeObjectReferencedSet(Standardtype standardtype) {
		HashMap<String, Object> objectReferencedSetMap = new HashMap<>();

		Set<Integer> standardsIds = new HashSet<Integer>();
		for (Standard obj : standardtype.getStandardsForStandardtype()) {

			standardsIds.add(obj.getId());
		}
		objectReferencedSetMap.put("standardsIds", standardsIds);

		return objectReferencedSetMap;
	}

	public Map<String, ?> loadStandardtypeClassReferencedSet(Standardtype standardtype) {
		HashMap<String, Object> classReferencedSetMap = new HashMap<>();
		classReferencedSetMap.put("standards", standardDAO.findAllStandards());

		return classReferencedSetMap;
	}

	public boolean isEquals(Standardtype standardtype, Object obj) {
		if (obj == standardtype)
			return true;
		if (!(obj instanceof Standardtype))
			return false;
		Standardtype comparedStandardtype = (Standardtype) obj;
		if (!CheckPropertyEqual(standardtype.getName(), comparedStandardtype.getName())) {
			return false;
		}
		return true;
	}

	public static <T> boolean CheckPropertyEqual(T originProperty, T comparedProperty) {
		// 基本类型经过参数传递后会自动装箱
		String[] className = originProperty.getClass().getName().split("\\.");
		if (className[0].equals("java") && className[1].equals("math")) {
			return ((Comparable) originProperty).compareTo(comparedProperty) == 0 ? true : false;
		} else {
			return originProperty.equals(comparedProperty);
		}
	}
}

